/**
 * 商品模块数据操作文件
 */

const { Op } = require('sequelize');
const { sequelize } = require('./common');
const { product_list } = sequelize.models;

/**
 * 添加
 * @param {*} model 
 * @returns 
 */
const add = model => product_list.create(model);

/**
 * 修改
 * @param {*} model 
 * @returns 
 */
const update = model => product_list.update(model, { where: { id: model.id } });

/**
 * 删除
 * @param {*} id 
 * @returns 
 */
const changeStatus = (id, status) => product_list.update({ status }, { where: { id } });

/**
 * 获取所有
 * @param {*} model 
 * @returns 
 */
const search = ({ name, price, end_price, status, class_id, pageNo, pageSize }) => product_list.findAndCountAll({
    order: [['id', 'desc']],
    limit: pageSize * 1,
    offset: (pageNo - 1) * pageSize,
    include: ['classify'],
    where: {
        ...(status && {
            status
        }),
        ...(name && {
            name: {
                [Op.like]: `%${name}%`
            }
        }),
        ...(price && {
            price: {
                [Op.gte]: price
            }
        }),
        ...(end_price && {
            price: {
                [Op.lte]: end_price
            }
        }),
        ...(class_id && {
            class_id
        })
    }
});

module.exports = {
    add,
    update,
    search,
    changeStatus,
}